package Threads.CAS;

import java.util.concurrent.atomic.AtomicInteger;


//cas实现
public class Account_impl2 implements Account{
    private AtomicInteger balance;

    public Account_impl2(Integer balance){
        this.balance=new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return balance.get();
    }

    //这个函数是重点，无锁实现取款
    //但是需要自旋
    @Override
    public void withdraw(Integer amount) {
        while (true){
            int i = balance.get();
            int res=i-amount;
            if ((balance.compareAndSet(i,res)))//该成功了，就break，否则就一直重试    cas操作是原子操作
                break;
        }
    }




    public static void main(String[] args) {
        Account.demo(new Account_impl(10000));
    }
}
